<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 16-12-9
 * Time: 下午5:20
 */

namespace common\services\outstock;

use common\entities\outstock\MyscrmDeliverySubOrderEntity;
use common\services\BaseService;
use common\support\CacheManage;
use common\repositories\config\ConfigSettingRepository;
use linslin\yii2\curl\Curl;
use common\repositories\outstock\DeliveryFlowRecordRepository;
use common\services\outstock\DeliveryOrderService;
use common\repositories\outstock\DeliveryOrderRepository;
use common\repositories\outstock\DeliverySubOrderRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\support\EmailHelper;
use common\models\common\ErpUserModel;
use common\services\myhtsq\ErpUserService;
use Yii;
use yii\helpers\ArrayHelper;
use common\entities\myhtsq\ContractManageEntity;
use common\services\common\MyscrmContractManageService;
use common\services\common\MyscrmOrganizationService;
use yii\log\Logger;
use common\services\config\ConfigSettingService;

/**
 * 出库流程
 */
class DeliveryOrderFlowService extends BaseService
{
    use \common\traits\FileLoggerTrait;
    const ACTION_FQ=20;
    const ACTION_QR=21;
    const ACTION_KT=22;
    const ACTION_SQ=23;
    const ACTION_DH=10;
    public static $actionMap = [
        self::ACTION_FQ => '发起',
        self::ACTION_DH => '打回',
        self::ACTION_QR => '确认',
        self::ACTION_KT => '开通',
        self::ACTION_SQ => '授权',
    ];
    public  static $actionToStatusMap= [
        self::ACTION_FQ => DeliveryOrderRepository::STATUS_YFQ,
        self::ACTION_DH => DeliveryOrderRepository::STATUS_YDH,
        self::ACTION_QR => DeliveryOrderRepository::STATUS_YQR,
        self::ACTION_KT => DeliveryOrderRepository::STATUS_YKT,
        self::ACTION_SQ => DeliveryOrderRepository::STATUS_YSQ,
    ];
    public  $operator;// 操作者模型
    private $_deliveryFlowRecordRepository;
    private $_deliveryOrderService;
    public function __construct(DeliveryOrderService $deliveryOrderService,DeliveryFlowRecordRepository $deliveryFlowRecordRepository, $config = [])
    {
        $this->_deliveryFlowRecordRepository = $deliveryFlowRecordRepository;
        $this->_deliveryOrderService=$deliveryOrderService;
        $logFile=sprintf('%s/logs/stock_out/%s/%s.log', \Yii::$app->getRuntimePath(), date('Ymd'),date('H') );
        $this->enableFileLog($logFile,1);//开启日志
        parent::__construct($config);
    }
    public function orderQr($deliveryGuid)
    {
        /** @var ConfigSettingService $configSettingService */
        $configSettingService = Yii::createObject(ConfigSettingService::className());
        $outStockConfig=$configSettingService->getCacheValue('OUT_STOCK_API_CONFIG',true);
        $params = ['delivery_guid' => $deliveryGuid];
        $curlRes = $this->_curlRequest('get', $outStockConfig['detail_api'], $params);
        if ($curlRes === false) {
            return $curlRes;
        }
        $deliveryOrderDetail = $curlRes;
        /*保存并拆分出库单*/
        $saveRes=$this->_deliveryOrderService->saveDeliveryOrder($deliveryOrderDetail);
        if($saveRes===false){
            $this->_deliveryOrderService->delDeliveryOrderByDeliveryGuid($saveRes['deliver_buguid'],true);
            return $saveRes;
        }
        $updateRes=$this->_updateDeliveryStatus($deliveryGuid,self::ACTION_QR,[]);
        $logData=[
            'sub_order_id'=>'',
            'delivery_guid' =>$deliveryGuid
        ];
        if($updateRes===false) {
            $this->_addFlowRecord(self::ACTION_QR,$logData,0);
            return $updateRes;
        }
        $this->_addFlowRecord(self::ACTION_QR,$logData,1);
        //添加发起记录
        $logData=[
            'sub_order_id'=>'',
            'operator_guid'=>$saveRes['deliver_guid'],
            'operator_name'=>$saveRes['deliver_name'],
            'operator_buname'=>$saveRes['deliver_buname'],
            'operator_buguid'=>$saveRes['deliver_buguid'],
            'delivery_guid' =>$deliveryGuid,
            'created_on'=>$saveRes['created_on']
        ];
        $this->_addFlowRecord(self::ACTION_FQ,$logData,1);
        return true;
    }
    public function orderDh($deliveryGuid,$remarks)
    {
        $updateRes=$this->_updateDeliveryStatus($deliveryGuid,self::ACTION_DH,['remarks'=>$remarks]);
        $logData=[
            'sub_order_id'=>'',
            'delivery_guid' =>$deliveryGuid,
            'remarks'=>$remarks
        ];
        if($updateRes){
            $this->_addFlowRecord(self::ACTION_DH,$logData,0);
            return $updateRes;
        }
        $this->_addFlowRecord(self::ACTION_DH,$logData,1);
        return $updateRes;
    }
    private function _updateDeliveryStatus($deliveryGuid,$action,$data){
        /** @var ConfigSettingService $configSettingService */
        $configSettingService = Yii::createObject(ConfigSettingService::className());
        $outStockConfig=$configSettingService->getCacheValue('OUT_STOCK_API_CONFIG',true);
        /*更新状态，不知道武汉那边为啥搞两个一模一样的接口～*/
        $params = [
            'status' => $action,
            'delivery_guid' => $deliveryGuid
        ];
        $curlRes=$this->_curlRequest('post',$outStockConfig['update_status_api'],$params);
        if($curlRes===false){
            //只是审批记录接口，失败就忽略
            $this->log('出库流程,请求远程更新状态接口失败，data:'.var_export($params,true));
            return $curlRes;
        }
        $params = [
            'action'=>$action,
            'action_user_id'=>$this->operator->UserGUID,
            'delivery_guid' =>$deliveryGuid
        ];
        if($action==self::ACTION_DH){
            $params['remarks']=$data['remarks'];
        }
        $this->log('开始调用远程审批记录接口,timestamp:'.time());
        $curlRes=$this->_curlRequest('post',$outStockConfig['approve_api'],$params);
        if($curlRes===false){
            //只是审批记录接口，失败就忽略
            $errMsg=$this->getErrMsg();
            $errMsg=is_array($errMsg)?var_export($errMsg,true):(String)$errMsg;
            $this->log('出库流程,请求远程审批记录接口失败,errMsg:'.$errMsg.'，data:'.var_export($params,true));
            //忽略错误，重置错误信息
            self::setAndReturn(0, '');
        }
        return true;
    }
    public function getApproveRecord($subOrderId){
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        $subOrder=$deliverySubOrderRepository->findBySubOrderId($subOrderId);
        if(!$subOrder){
            return self::setAndReturn(__LINE__,'无法获取待办信息');
        }
        $allRecords=[];
        $orderRecords=$this->_deliveryFlowRecordRepository->getOrderRecord($subOrder->delivery_guid);
        foreach ($orderRecords as $key=>$item){
            switch ($item['action']){
                case self::ACTION_FQ:
                    $item['result'] = '发起';
                    $item['suggestion'] = '发起说明：无';
                    break;
                case self::ACTION_DH:
                    $item['result'] = '审批不通过';
                    $item['suggestion'] = '审批意见：不同意' . ($item['remarks'] ? '，' . $item['remarks'] : '');
                    break;
                case self::ACTION_QR:
                    $item['result'] = '审批通过';
                    $item['suggestion'] = '审批意见：同意';
                    break;
            }
            $item['action'] = self::$actionMap[$item['action']];
            $allRecords[]=$item;
        }
        return $allRecords;
    }
    /**
     * 租户添加完成
     * @param $orgId
     * @param $orderCode
     * @param $orgName
     * @param $orgCode
     * @param $password
     * @param $operatorId
     * @return bool
     */
    public function createOrg($orgId, $orderCode, $orgName, $orgCode, $password, $userGuid = null)
    {
        $this->log('开通租户，orgId:'.$orgId.',orderCode:'.$orderCode.',orgName:'.$orgName.',orgCode:'.$orgCode.',password:'.$password.',userGuid:'.$userGuid);
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        /** @var DeliveryOrderRepository $deliveryOrderRepository */
        $deliveryOrderRepository=\Yii::createObject(DeliveryOrderRepository::className());
        $subOrder=$deliverySubOrderRepository->findDetailBySubOrderCode($orderCode);
        if (empty($subOrder)) {
            return $this->setAndReturn(-1, "该待办单不存在");
        }
        $this->log('开通租户，subOrder:'.var_export($subOrder,true));
        $deliveryOrder=$deliveryOrderRepository->findDeliveryOrderByDeliveryGuid($subOrder['delivery_guid']);
        if (empty($deliveryOrder)) {
            return $this->setAndReturn(-1, "该出库单不存在");
        }
        //一个单号关联一个租户开通
        if ($deliveryOrder->is_new_org!=1) {
            return $this->setAndReturn(-1, "只有未开通租户的出库单才允许执行次操作");
        }
        //一个单号关联一个租户开通
        if (!empty($deliveryOrder->org_id)) {
            return $this->setAndReturn(-1, "该单号已经被关联过了");
        }
        //外部传的userguid,通常来自接口
        if (!empty($userGuid)) {
            $operatorModel = $this->getUserById($userGuid);
            if (empty($operatorModel)) {
                return $this->setAndReturn(-1, "无法获取操作人信息！");
            }
        } else {
            /* @var ErpUserModel $operatorModel */
            $operatorModel = \Yii::createObject(ErpUserModel::className());
            $operatorModel->UserGuid = \Yii::$app->user->identity->userguid;
            $operatorModel->UserName = \Yii::$app->user->identity->username;
            $operatorModel->DepartmentGUID = \Yii::$app->user->identity->departmentGuid;
            $operatorModel->DepartmentName = \Yii::$app->user->identity->departmentName;
            $operatorModel->BUGUID = \Yii::$app->user->identity->buGuid;
            $operatorModel->BUName = \Yii::$app->user->identity->buName;
        }
        $this->operator = $operatorModel;
        if ($subOrder['flow_status']>=DeliveryOrderRepository::STATUS_YKT) {
            return self::setAndReturn(__LINE__, '已开通租户，请勿重复操作。');
        }
        //回填租户ID
        $deliveryOrder->org_id = $orgId;
        $deliveryOrder->org_code = $orgCode;
        $deliveryOrder->org_name = $orgName;
        $saveRes=$deliveryOrder->save();
        if ($saveRes===false) {
            return $this->setAndReturn(-1, "更新出库单信息失败！");
        }
        if ($this->_doAction($subOrder['delivery_guid'],$subOrder['sub_order_id'],self::ACTION_KT,'') === false) {
            return false;
        }
        return true;
    }
    /**
     *  授权添加完之后的操作
     * @param $orderCode
     * @param $contractCode
     * @param $userGuid
     * @param $beginOn
     * @param $endOn
     * @return bool
     */
    public function orderSQ($orderCode, $contractCode, $userGuid, $beginOn, $endOn)
    {
        $this->log('新增授权，orderCode:'.$orderCode.',contractCode:'.$contractCode.',userGuid:'.$userGuid.',beginOn:'.$beginOn.',endOn:'.$endOn);
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        $subOrder=$deliverySubOrderRepository->findDetailBySubOrderCode($orderCode);
        if (empty($subOrder)) {
            return $this->setAndReturn(-1, "该出库单不存在");
        }
        $this->log('新增授权，subOrder:'.var_export($subOrder,true));
        //发起授权
        //新租户，非已开通状态，不允许授权
        if ($subOrder['is_new_org']==1&&$subOrder['flow_status']!= DeliveryOrderRepository::STATUS_YKT) {
            $this->log('新租户，非已开通状态，不允许授权');
            return $this->setAndReturn(-1, "未开通租户");
        }
        //老租户，非已确认状态，不允许授权
        if ($subOrder['is_new_org']==0&&$subOrder['flow_status']< DeliveryOrderRepository::STATUS_YKT) {
            $this->log('老租户，非已确认状态，不允许授权');
            return $this->setAndReturn(-1, "未确认出库单");
        }
        //外部传的userguid,通常来自接口
        if (!empty($userGuid)) {
            $operatorModel = $this->getUserById($userGuid);
            if (empty($operatorModel)) {
                return $this->setAndReturn(-1, "无法获取操作人信息！");
            }
        } else {
            /* @var ErpUserModel $operatorModel */
            $operatorModel = \Yii::createObject(ErpUserModel::className());
            $operatorModel->UserGuid = \Yii::$app->user->identity->userguid;
            $operatorModel->UserName = \Yii::$app->user->identity->username;
            $operatorModel->DepartmentGUID = \Yii::$app->user->identity->departmentGuid;
            $operatorModel->DepartmentName = \Yii::$app->user->identity->departmentName;
            $operatorModel->BUGUID = \Yii::$app->user->identity->buGuid;
            $operatorModel->BUName = \Yii::$app->user->identity->buName;
        }
        $this->operator = $operatorModel;
        if ($this->_doAction($subOrder['delivery_guid'],$subOrder['sub_order_id'],self::ACTION_SQ,'') === false) {
            return false;
        }
        return true;
    }
    private function _curlRequest($method,$url,$params){
        $curl = new Curl();
        $curl->setOption(CURLOPT_CONNECTTIMEOUT,60);
        $curl->setOption(CURLOPT_TIMEOUT,60);
        try{
            if($method=='get'){
                $res = $curl->get($this->_getUrlWithParams($url,$params), true);
            }else{
                $header[] = 'Content-Type:application/x-www-form-urlencoded';
                $curl->setOption(CURLOPT_HTTPHEADER,$header);
                $curl->setOption(CURLOPT_POST,1);
                $postDataStr='';
                foreach ($params as $pkey=>$pvalue){
                    $postDataStr.=$pkey.'='.urlencode($pvalue).'&';
                }
                $postDataStr=trim($postDataStr,'&');
                $curl->setOption(CURLOPT_POSTFIELDS,$postDataStr);
                $res = $curl->post($this->_getUrlWithParams($url), true);
            }
        }catch (\Exception $e){
            $errCode=$e->getCode();
            if($errCode==CURLE_OPERATION_TIMEDOUT||$errCode==CURLE_OPERATION_TIMEOUTED) {
                return self::setAndReturn(__LINE__, '请求远程接口超时,请稍后再试！');
            }else{
                return self::setAndReturn(__LINE__, $e->getMessage());
            }
        }
        $res = json_decode($res, true);
        if ($res && isset($res['userData']['success']) && ($res['userData']['success'] === true)) {
            return $res['userData']['data'];
        }
        $errMsg=isset($res['userData']['message'])&&!empty($res['userData']['message'])?$res['userData']['message']:'远程接口返回数据解析失败！';
        return self::setAndReturn(__LINE__, $errMsg);
    }
    private function _getUrlWithParams($url,$params=[]){
        if(empty($params)){
            return $url;
        }
        if (strpos($url, '?') !== false) {
            $url = $url . '&';
        } else {
            $url = $url . '?';
        }
        $queryString='';
        foreach ($params as $key=>$value){
            $queryString.='&'.$key.'='.urlencode($value);
        }
        return $url.trim($queryString,'&');
    }
    /**
     * @return bool
     */
    private function _doAction($deliveryOrderGuid,$subOrderId,$action,$remarks='')
    {
        $this->log('出库操作,subOrderGuid:'.$subOrderId.',action:'.$action.',remarks:'.$remarks);
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        $flowStatus=isset(self::$actionToStatusMap[$action])?self::$actionToStatusMap[$action]:0;
        $transaction = MyscrmDeliverySubOrderEntity::getDb()->beginTransaction();
        try {
            if($action==self::ACTION_KT) {
                //开通操作要对所有的待办进行状态更新
                $updateRes=$deliverySubOrderRepository->updateSubOrdersFlowStatusByOrderId($deliveryOrderGuid, $flowStatus);
            }else{
                $updateRes=$deliverySubOrderRepository->updateSubOrderFlowStatusById($subOrderId, $flowStatus);
            }
            if ($updateRes === false) {
                $transaction->rollBack();
                $errors = $deliverySubOrderRepository->getFirstErrors();
                $this->log('出库操作，保存待办状态失败,sub_order_id' . $subOrderId);
                return self::setAndReturn(__LINE__, implode(';', $errors));
            }
            $recordData=['delivery_guid'=>$deliveryOrderGuid,'sub_order_id'=>$subOrderId,'remarks'=>$remarks];
            if (false===$this->_addFlowRecord($action,$recordData,1)){
                $transaction->rollBack();
                $this->log('出库操作，添加出库流水发生错误：'.var_export($recordData,true),[],Logger::LEVEL_ERROR);
                return false;
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->log('出库操作，更新待办发生错误：'.(String)$e,[],Logger::LEVEL_ERROR);
            $this->_addFlowRecord($action,['delivery_guid'=>$deliveryOrderGuid,'sub_order_id'=>$subOrderId,'remarks'=>$remarks],0);
            return self::setAndReturn($e->getCode(), $e->getMessage());
        }
        if($action==self::ACTION_SQ){
            $notDoneCount=$deliverySubOrderRepository->getNotDoneCount($deliveryOrderGuid);
            if($notDoneCount==0){
                $this->log('出库操作，调用远程接口更新出库单状态,timestamp:'.time());
                $updateRes=$this->_updateDeliveryStatus($deliveryOrderGuid,self::ACTION_SQ,[]);
                $this->log('调用远程接口更新出库单状态结束,timestamp:'.time());
                if($updateRes===false){
                    $this->log('出库操作，调用远程接口更新出库单状态发生错误',[],Logger::LEVEL_ERROR);
                }
            }
        }
        return true;
    }

    /**
     * 创建流程步骤
     * @return bool|string
     */
    private function _addFlowRecord($action,$data,$isSuccess=1)
    {
        $flowData = [
            'action' => $action,
            'sub_order_id' => isset($data['sub_order_id']) ? $data['sub_order_id'] : '',
            'delivery_guid' => $data['delivery_guid'],
            'remarks' => isset($data['remarks']) ? $data['remarks'] : '',
            'created_on' => isset($data['created_on']) ? $data['created_on'] : date('Y-m-d H:i:s', time()),
            'isSuccess' => $isSuccess
        ];
        if($this->operator) {
            $flowData['operator_guid'] = isset($data['deliver_guid']) ? $data['deliver_guid'] : $this->operator->UserGUID;
            $flowData['operator_name'] = isset($data['operator_name']) ? $data['operator_name'] : $this->operator->UserName;
            $flowData['operator_buname'] = isset($data['operator_buname']) ? $data['operator_buname'] : $this->operator->BUName;
            $flowData['operator_buguid'] = isset($data['operator_buguid']) ? $data['operator_buguid'] : $this->operator->BUGUID;
        }else{
            $flowData['operator_guid'] = isset($data['deliver_guid']) ? $data['deliver_guid'] : '';
            $flowData['operator_name'] = isset($data['operator_name']) ? $data['operator_name'] : '';
            $flowData['operator_buname'] = isset($data['operator_buname']) ? $data['operator_buname'] : '';
            $flowData['operator_buguid'] = isset($data['operator_buguid']) ? $data['operator_buguid'] : '';
        }
        $this->log('创建出库流水，flowData:'.var_export($flowData,true));
        return $this->_deliveryFlowRecordRepository->addRecord($flowData);
    }
    /**
     * 获取 LDAP 用户信息
     * @param $userId
     * @return ErpUserModel|boolean
     */
    private function getUserById($userId)
    {
        /** @var ErpUserService $service */
        $service = Yii::createObject(ErpUserService::className());
        $user = $service->getUserById($userId);
        if (empty($user)) {
            return self::setAndReturn(__LINE__, '用户 ' . $userId . ' 不存在');
        }
        if (empty($user['Email'])) {
            return self::setAndReturn(__LINE__, '用户的邮件未设置。');
        }
        return $user;
    }
    /**
     * 开通通知
     * @param $orgName
     * @param $orgCode
     * @param $password
     * @return bool
     */
    public function sendKtEmail($orderCode,$orgName, $orgCode, $password)
    {
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        $deliverySubOrder=$deliverySubOrderRepository->findDetailBySubOrderCode($orderCode);
        $this->log('开通邮件通知，deliver_guid:'.$deliverySubOrder['deliver_guid'].',org_name:'.$orgName.',org_code:'.$orgCode.',password:'.$password);
        $user = $this->getUserById($deliverySubOrder['deliver_guid']);
        if (empty($user)) {
            $this->log('无法获取出库申请人信息，邮件发送失败！');
            return self::setAndReturn(__LINE__,'无法获取出库申请人信息，邮件发送失败！');
        }
        $this->log('申请人信息：'.var_export($user,true));
        $subject = sprintf('申请开通云客授权—%s，已开通租户', $deliverySubOrder['customer_name']);
        $template = '【租  户】：%s<br />【企业号】：%s<br />【密  码】：%s<br />';
        $html = sprintf($template,
            $orgName, $orgCode, $password
        );
        $sendToEmailArr=[];
        $sendToEmailArr[]=$user['Email'];
        if(!empty($deliverySubOrder['sign_people_mail'])){
            $sendToEmailArr[]=$deliverySubOrder['sign_people_mail'];
        }
        if(!empty($deliverySubOrder['adviser_mail'])){
            $sendToEmailArr[]=$deliverySubOrder['adviser_mail'];
        }
        $products = $this->getProducts($deliverySubOrder['sub_order_id']);
        //是否有在线开盘产品
        $haveKaiPan=false;
        foreach ($products as $product){
            if($product['application_id']=='9418728e-6760-4a67-8030-d0884a3ba1ff'){
                $haveKaiPan=true;
                break;
            }
        }
        if($haveKaiPan){
            /** @var ConfigSettingService $configSettingService */
            $configSettingService = Yii::createObject(ConfigSettingService::className());
            $kaiPanNoticeEmail=$configSettingService->getCacheValue('KAIPAN_AUTHORIZE_EMAIL_NOTICE');
            if($kaiPanNoticeEmail){
                $sendToEmailArr[]=$kaiPanNoticeEmail;
            }else{
                $this->error('无法获取在线开盘授权邮件提醒特定人email');
            }
        }
        $this->log('开通邮件接收人：'.var_export($sendToEmailArr,true));
        return $this->emailTo($sendToEmailArr, $subject, $html);
    }
    /**
     * 先创建邮件内容并且校验数据
     * @param $beginOn
     * @param $endOn
     * @return bool|array
     */
    public function sendSqEmail($orderCode,$contractCode,$beginOn, $endOn)
    {
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        $deliverySubOrder=$deliverySubOrderRepository->findDetailBySubOrderCode($orderCode);
        $this->log('新增授权邮件通知,deliverySubOrder:'.var_export($deliverySubOrder,true).',beginOn:'.$beginOn.',endOn:'.$endOn);
        $user = $this->getUserById($deliverySubOrder['deliver_guid']);
        if (empty($user)) {
            $this->log('新增授权邮件通知，无法获取申请人信息');
            return self::setAndReturn(__LINE__, '未新增授权邮件通知，无法获取申请人信息');
        }
        $products = $this->getProducts($deliverySubOrder['sub_order_id']);
        $this->log('新增授权邮件通知，授权产品：'.var_export($products,true));
        if (empty($products)) {
            $this->log('新增授权邮件通知，未找到单据的授权信息,发送邮件通知失败！');
            return self::setAndReturn(__LINE__, '未找到单据的授权信息,发送邮件通知失败！');
        }
        //是否有在线开盘产品
        $haveKaiPan=false;
        foreach ($products as $product){
            if($product['application_id']=='9418728e-6760-4a67-8030-d0884a3ba1ff'){
                $haveKaiPan=true;
                break;
            }
        }
        $html = '';
        if ($deliverySubOrder['erp_contract_id']) {
            $contract = $this->getContract($deliverySubOrder,$deliverySubOrder['business_pattern']);
            if(empty($contract)){
                $contract = $this->getContractByContractCode($contractCode);
            }
            if (empty($contract)) {
                $this->log('新增授权邮件通知，找不到对应的合同信息 contract code:'.$deliverySubOrder['erp_contract_code'].',发送邮件通知失败！');
                return self::setAndReturn(__LINE__, '找不到对应的合同信息 contract code:'.$deliverySubOrder['erp_contract_code'].',发送邮件通知失败！');
            }
            if($contract->area_id){
                $area_name = $this->_getAreaNameByAreaId($contract->area_id);
            }else{
                $area_name='';
            }
            $orgName = $this->_getOrgNameByOrgId($deliverySubOrder['org_id']);
            if($orgName===false){
                $this->log('新增授权邮件通知，无法获取租户信息');
                return self::setAndReturn(__LINE__, '新增授权邮件通知，无法获取租户信息！');
            }
            $template = '<br /><br />【出库单编号】：%s<br />【区    域】：%s<br />【租    户】：%s<br />【企 业 号】：%s<br />【合 同 号】：%s<br />【合同甲方】：%s<br />【租    期】：%s到%s<br />';
            $html .= sprintf($template,
                $deliverySubOrder['order_code'],
                $area_name,
                $orgName,
                $deliverySubOrder['org_code'],
                $deliverySubOrder['erp_contract_code'],
                $deliverySubOrder['customer_full_name'],
                substr($beginOn, 0, 10),
                substr($endOn, 0, 10)
            );
        } else {
            $orgName = $this->_getOrgNameByOrgId($deliverySubOrder['org_id']);
            $template = '<br /><br />【出库单编号】：%s<br />【租    户】：%s<br />【企 业 号】：%s<br />';
            $html .= sprintf($template,
                $deliverySubOrder['order_code'],
                $orgName,
                $deliverySubOrder['org_code']
            );
        }

        $info = [];
        foreach ($products as $product) {
            //未申请授权的应用，不需要展示在邮件中。
            if ($product['apply_num'] <= 0) {
                continue;
            }
            $bind_project = [];
            if ($product['bind_project']) {
                foreach ($product['bind_project'] as $p) {
                    $bind_project[] = $p['proj_name'];
                }
            }
            if ($bind_project) {
                $info[] = sprintf('• %s：%d个授权（%s）', $product['application_name'], $product['apply_num'], implode('，', $bind_project));
            } else {
                $info[] = sprintf('• %s：%d个授权', $product['application_name'], $product['apply_num']);
            }
        }

        $subject = sprintf('申请开通云客授权—%s，已开通授权', $deliverySubOrder['customer_name']);
        $template = '<br /><br />授权信息如下：<br />%s<br />';
        $html .= sprintf($template,
            implode("<br />", $info)
        );
        $this->log('新增授权邮件通知，邮件内容：'.$html);
        $sendToEmailArr=[];
        $sendToEmailArr[]=$user['Email'];
        if(!empty($deliverySubOrder['sign_people_mail'])){
            $sendToEmailArr[]=$deliverySubOrder['sign_people_mail'];
        }
        if(!empty($deliverySubOrder['adviser_mail'])){
            $sendToEmailArr[]=$deliverySubOrder['adviser_mail'];
        }
        if($haveKaiPan){
            /** @var ConfigSettingService $configSettingService */
            $configSettingService = Yii::createObject(ConfigSettingService::className());
            $kaiPanNoticeEmail=$configSettingService->getCacheValue('KAIPAN_AUTHORIZE_EMAIL_NOTICE');
            if($kaiPanNoticeEmail){
                $sendToEmailArr[]=$kaiPanNoticeEmail;
            }else{
                $this->error('无法获取在线开盘授权邮件提醒特定人email');
            }
        }
        $this->log('开通邮件接收人：'.var_export($sendToEmailArr,true));
        return $this->emailTo($sendToEmailArr, $subject, $html);
    }
    /**
     * 获取授权产品
     * @param $orderId
     * @return \common\entities\outstock\MyscrmOutStockProductEntity[]
     */
    private function getProducts($subOrderId)
    {
        return $this->_deliveryOrderService->getProducts($subOrderId);
    }

    /**
     * 获取单据关联合同
     * @param $contractCode
     * @return ContractManageEntity
     */
    private function getContract($deliverySubOrder,$businessPattern)
    {
        /** @var MyscrmContractManageService $service */
        $service = Yii::createObject(MyscrmContractManageService::className());
        if($businessPattern==DeliveryOrderRepository::$businessPatternMap['联营']){
            return $service->getContractBySignNumber($deliverySubOrder['erp_contract_code']);
        }else{
            return $service->getContractByContractIdOrErpContractId($deliverySubOrder['erp_contract_id']);
        }
    }
    private function getContractByContractCode($contractCode)
    {
        if($contractCode&&strpos($contractCode,'-')!==false)
        {
            /** @var MyscrmContractManageService $service */
            $service = Yii::createObject(MyscrmContractManageService::className());
            return $service->getContractManageByCode($contractCode);
        }
        return null;
    }
    private function emailTo($to, $subject, $body)
    {
        Yii::$app->mailer->messageConfig['from'] = ['yunkeadmin@mysoft.com.cn' => 'hetong-yunke@mingyuanyun.com'];

        return EmailHelper::send($to, $subject, $body);
    }
    /**
     * 通过合同查询区域
     * @param $contractCode
     * @return bool|string
     * @throws \yii\base\InvalidConfigException
     */
    private function _getAreaNameByAreaId($areaId)
    {
        if (empty($areaId)) {
            return self::setAndReturn(__LINE__, '区域id不能为空');
        }
        /** @var MyscrmContractManageService $service */
        $service = Yii::createObject(MyscrmContractManageService::className());
        return $service->getBunameByBuguid($areaId);
    }

    /**
     * 查询租户名
     * @param $orgId
     * @return bool|mixed
     * @throws \yii\base\InvalidConfigException
     */
    private function _getOrgNameByOrgId($orgId)
    {
        /** @var MyscrmOrganizationService $service */
        $service = Yii::createObject(MyscrmOrganizationService::className());
        $org = $service->getOrgById($orgId);
        if (!empty($org)) {
            return $org->FriendlyName;
        } else {
            return self::setAndReturn(__LINE__, '没有此租户，orgid:' . $orgId);
        }
    }
}